import axios from 'axios';

// 创建axios实例
const instance = axios.create({
  baseURL: 'http://localhost:3000', // 根据实际情况调整
  withCredentials: true // 允许携带cookie（用于refreshToken）
});

// 请求拦截器：自动带上accessToken
instance.interceptors.request.use(
  config => {
    const token = localStorage.getItem('accessToken');
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token;
    }
    return config;
  },
  error => Promise.reject(error)
);

// 响应拦截器：自动无感刷新token
let isRefreshing = false;
let requests = [];

instance.interceptors.response.use(
  response => response,
  async error => {
    const originalRequest = error.config;
    if (error.response && error.response.status === 401 && !originalRequest._retry) {
      if (isRefreshing) {
        // 正在刷新，队列等待
        return new Promise(resolve => {
          requests.push(token => {
            originalRequest.headers['Authorization'] = 'Bearer ' + token;
            resolve(instance(originalRequest));
          });
        });
      }
      originalRequest._retry = true;
      isRefreshing = true;
      try {
        const res = await instance.post('/users/refresh-token');
        const newToken = res.data.accessToken;
        localStorage.setItem('accessToken', newToken);
        // 重新执行队列
        requests.forEach(cb => cb(newToken));
        requests = [];
        // 重试原请求
        originalRequest.headers['Authorization'] = 'Bearer ' + newToken;
        return instance(originalRequest);
      } catch (e) {
        // 刷新失败，清除token并跳转登录
        localStorage.removeItem('accessToken');
        window.location.href = '/';
        return Promise.reject(e);
      } finally {
        isRefreshing = false;
      }
    }
    return Promise.reject(error);
  }
);

export default instance; 